package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private HttpSession session;

    @Autowired
    private UserService userService;

    //TODO 验证码发送问题
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user){
        String phone = user.getPhone();
        if(phone!=null){
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            //TODO 日志级别设置为warn了
            log.warn("code={}",code);
            session.setAttribute(phone,code);
            return R.success("验证码发送成功");
        }
        return R.error("手机号不正确,验证码发送失败");
    }

    @PostMapping("/login")
    public R login(@RequestBody Map map){
        //TODO 前端返回数据问题 phone:{"phone":"号码","code":"验证码"}
        HashMap hashMap =(HashMap) map.get("phone");
        String phone = hashMap.get("phone").toString();
        String code = hashMap.get("code").toString();
        Object attribute =  session.getAttribute(phone);
        if(attribute!=null&&attribute.equals(code)){
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User res = userService.getOne(wrapper);
            if(res==null){
                res=new User();
                res.setPhone(phone);
                res.setStatus(1);
                userService.save(res);
            }
            //移除验证码,防止单一验证码持续有效
            session.removeAttribute(phone);
            session.setAttribute("user",res.getId());
            return R.success(res);
        }
        return R.error("登录失败");
    }

    @PostMapping("/loginout")
    public R logout(){
        return R.success("退出登录成功");
    }



}
